package com.alan.netty.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author weiBin
 * @date 2018/11/5
 */
public class SingleServer {
    static int port = 8081;

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        System.out.println("服务器在端口[" + port + "]等待客户请求......");
        int i = 0;
        try {
            serverSocket = new ServerSocket(port);
            Socket socket = serverSocket.accept();
            handleRequest(++i, socket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleRequest(int clientNo, Socket socket) {
        PrintWriter printWriter = null;
        BufferedReader reader = null;
        try {
            printWriter = new PrintWriter(socket.getOutputStream(), true);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                if ("Quit".equals(inputLine)) {
                    System.out.println(String.format("客户端%s关闭!", clientNo));
                    printWriter.close();
                    reader.close();
                    socket.close();
                    System.exit(1);
                    break;
                } else {
                    System.out.println(String.format("客户端%s输入的是%s", clientNo, inputLine));
                    printWriter.println("来自服务器端的响应:" + inputLine);
                }
            }
        } catch (IOException e) {

        }
    }
}
